﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Kingdom
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Election;
using TaleWorlds.CampaignSystem.GameState;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Party.PartyComponents;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;
using TaleWorlds.SaveSystem.Load;

#nullable disable
namespace TaleWorlds.CampaignSystem
{
  public sealed class Kingdom : MBObjectBase, IFaction
  {
    [SaveableField(10)]
    private MBList<KingdomDecision> _unresolvedDecisions = new MBList<KingdomDecision>();
    [CachedData]
    private List<StanceLink> _stances;
    [CachedData]
    private MBList<Town> _fiefsCache;
    [CachedData]
    private MBList<Village> _villagesCache;
    [CachedData]
    private MBList<Settlement> _settlementsCache;
    [CachedData]
    private MBList<Hero> _heroesCache;
    [CachedData]
    private MBList<Hero> _lordsCache;
    [CachedData]
    private MBList<WarPartyComponent> _warPartyComponentsCache;
    [CachedData]
    private MBList<Clan> _clans;
    [SaveableField(18)]
    private Clan _rulingClan;
    [SaveableField(20)]
    private MBList<Army> _armies;
    [CachedData]
    private float _distanceToClosestNonAllyFortificationCache;
    [CachedData]
    internal bool _distanceToClosestNonAllyFortificationCacheDirty = true;
    [SaveableField(23)]
    public int PoliticalStagnation;
    [SaveableField(26)]
    private MBList<PolicyObject> _activePolicies;
    [SaveableField(29)]
    private bool _isEliminated;
    [SaveableField(60)]
    private float _aggressiveness;
    [CachedData]
    private Settlement _kingdomMidSettlement;
    [SaveableField(80)]
    private int _tributeWallet;
    [SaveableField(81)]
    private int _kingdomBudgetWallet;

    internal static void AutoGeneratedStaticCollectObjectsKingdom(
      object o,
      List<object> collectedObjects)
    {
      ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
    }

    protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
    {
      base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      collectedObjects.Add((object) this._unresolvedDecisions);
      collectedObjects.Add((object) this._rulingClan);
      collectedObjects.Add((object) this._armies);
      collectedObjects.Add((object) this._activePolicies);
      collectedObjects.Add((object) this.Name);
      collectedObjects.Add((object) this.InformalName);
      collectedObjects.Add((object) this.EncyclopediaText);
      collectedObjects.Add((object) this.EncyclopediaTitle);
      collectedObjects.Add((object) this.EncyclopediaRulerTitle);
      collectedObjects.Add((object) this.Culture);
      collectedObjects.Add((object) this.InitialHomeLand);
      collectedObjects.Add((object) this.Banner);
      CampaignTime.AutoGeneratedStaticCollectObjectsCampaignTime((object) this.LastKingdomDecisionConclusionDate, collectedObjects);
      CampaignTime.AutoGeneratedStaticCollectObjectsCampaignTime((object) this.LastMercenaryOfferTime, collectedObjects);
      CampaignTime.AutoGeneratedStaticCollectObjectsCampaignTime((object) this.NotAttackableByPlayerUntilTime, collectedObjects);
    }

    internal static object AutoGeneratedGetMemberValueName(object o) => (object) ((Kingdom) o).Name;

    internal static object AutoGeneratedGetMemberValueInformalName(object o)
    {
      return (object) ((Kingdom) o).InformalName;
    }

    internal static object AutoGeneratedGetMemberValueEncyclopediaText(object o)
    {
      return (object) ((Kingdom) o).EncyclopediaText;
    }

    internal static object AutoGeneratedGetMemberValueEncyclopediaTitle(object o)
    {
      return (object) ((Kingdom) o).EncyclopediaTitle;
    }

    internal static object AutoGeneratedGetMemberValueEncyclopediaRulerTitle(object o)
    {
      return (object) ((Kingdom) o).EncyclopediaRulerTitle;
    }

    internal static object AutoGeneratedGetMemberValueCulture(object o)
    {
      return (object) ((Kingdom) o).Culture;
    }

    internal static object AutoGeneratedGetMemberValueInitialHomeLand(object o)
    {
      return (object) ((Kingdom) o).InitialHomeLand;
    }

    internal static object AutoGeneratedGetMemberValueLabelColor(object o)
    {
      return (object) ((Kingdom) o).LabelColor;
    }

    internal static object AutoGeneratedGetMemberValueColor(object o)
    {
      return (object) ((Kingdom) o).Color;
    }

    internal static object AutoGeneratedGetMemberValueColor2(object o)
    {
      return (object) ((Kingdom) o).Color2;
    }

    internal static object AutoGeneratedGetMemberValueAlternativeColor(object o)
    {
      return (object) ((Kingdom) o).AlternativeColor;
    }

    internal static object AutoGeneratedGetMemberValueAlternativeColor2(object o)
    {
      return (object) ((Kingdom) o).AlternativeColor2;
    }

    internal static object AutoGeneratedGetMemberValuePrimaryBannerColor(object o)
    {
      return (object) ((Kingdom) o).PrimaryBannerColor;
    }

    internal static object AutoGeneratedGetMemberValueSecondaryBannerColor(object o)
    {
      return (object) ((Kingdom) o).SecondaryBannerColor;
    }

    internal static object AutoGeneratedGetMemberValueMainHeroCrimeRating(object o)
    {
      return (object) ((Kingdom) o).MainHeroCrimeRating;
    }

    internal static object AutoGeneratedGetMemberValueBanner(object o)
    {
      return (object) ((Kingdom) o).Banner;
    }

    internal static object AutoGeneratedGetMemberValueLastArmyCreationDay(object o)
    {
      return (object) ((Kingdom) o).LastArmyCreationDay;
    }

    internal static object AutoGeneratedGetMemberValueLastKingdomDecisionConclusionDate(object o)
    {
      return (object) ((Kingdom) o).LastKingdomDecisionConclusionDate;
    }

    internal static object AutoGeneratedGetMemberValueLastMercenaryOfferTime(object o)
    {
      return (object) ((Kingdom) o).LastMercenaryOfferTime;
    }

    internal static object AutoGeneratedGetMemberValueNotAttackableByPlayerUntilTime(object o)
    {
      return (object) ((Kingdom) o).NotAttackableByPlayerUntilTime;
    }

    internal static object AutoGeneratedGetMemberValueMercenaryWallet(object o)
    {
      return (object) ((Kingdom) o).MercenaryWallet;
    }

    internal static object AutoGeneratedGetMemberValuePoliticalStagnation(object o)
    {
      return (object) ((Kingdom) o).PoliticalStagnation;
    }

    internal static object AutoGeneratedGetMemberValue_unresolvedDecisions(object o)
    {
      return (object) ((Kingdom) o)._unresolvedDecisions;
    }

    internal static object AutoGeneratedGetMemberValue_rulingClan(object o)
    {
      return (object) ((Kingdom) o)._rulingClan;
    }

    internal static object AutoGeneratedGetMemberValue_armies(object o)
    {
      return (object) ((Kingdom) o)._armies;
    }

    internal static object AutoGeneratedGetMemberValue_activePolicies(object o)
    {
      return (object) ((Kingdom) o)._activePolicies;
    }

    internal static object AutoGeneratedGetMemberValue_isEliminated(object o)
    {
      return (object) ((Kingdom) o)._isEliminated;
    }

    internal static object AutoGeneratedGetMemberValue_aggressiveness(object o)
    {
      return (object) ((Kingdom) o)._aggressiveness;
    }

    internal static object AutoGeneratedGetMemberValue_tributeWallet(object o)
    {
      return (object) ((Kingdom) o)._tributeWallet;
    }

    internal static object AutoGeneratedGetMemberValue_kingdomBudgetWallet(object o)
    {
      return (object) ((Kingdom) o)._kingdomBudgetWallet;
    }

    [SaveableProperty(1)]
    public TextObject Name { get; private set; }

    [SaveableProperty(2)]
    public TextObject InformalName { get; private set; }

    [SaveableProperty(3)]
    public TextObject EncyclopediaText { get; private set; }

    [SaveableProperty(4)]
    public TextObject EncyclopediaTitle { get; private set; }

    [SaveableProperty(5)]
    public TextObject EncyclopediaRulerTitle { get; private set; }

    public string EncyclopediaLink
    {
      get
      {
        return Campaign.Current.EncyclopediaManager.GetIdentifier(typeof (Kingdom)) + "-" + this.StringId;
      }
    }

    public TextObject EncyclopediaLinkWithName
    {
      get => HyperlinkTexts.GetKingdomHyperlinkText(this.EncyclopediaLink, this.InformalName);
    }

    public MBReadOnlyList<KingdomDecision> UnresolvedDecisions
    {
      get => (MBReadOnlyList<KingdomDecision>) this._unresolvedDecisions;
    }

    [SaveableProperty(6)]
    public CultureObject Culture { get; private set; }

    [SaveableProperty(17)]
    public Settlement InitialHomeLand { get; private set; }

    public Vec2 InitialPosition => this.InitialHomeLand.GatePosition;

    public bool IsMapFaction => true;

    [SaveableProperty(8)]
    public uint LabelColor { get; private set; }

    [SaveableProperty(9)]
    public uint Color { get; private set; }

    [SaveableProperty(10)]
    public uint Color2 { get; private set; }

    [SaveableProperty(11)]
    public uint AlternativeColor { get; private set; }

    [SaveableProperty(12)]
    public uint AlternativeColor2 { get; private set; }

    [SaveableProperty(13)]
    public uint PrimaryBannerColor { get; private set; }

    [SaveableProperty(14)]
    public uint SecondaryBannerColor { get; private set; }

    [SaveableProperty(15)]
    public float MainHeroCrimeRating { get; set; }

    public IEnumerable<StanceLink> Stances => (IEnumerable<StanceLink>) this._stances;

    public MBReadOnlyList<Town> Fiefs => (MBReadOnlyList<Town>) this._fiefsCache;

    public MBReadOnlyList<Village> Villages => (MBReadOnlyList<Village>) this._villagesCache;

    public MBReadOnlyList<Settlement> Settlements
    {
      get => (MBReadOnlyList<Settlement>) this._settlementsCache;
    }

    public MBReadOnlyList<Hero> Heroes => (MBReadOnlyList<Hero>) this._heroesCache;

    public MBReadOnlyList<Hero> Lords => (MBReadOnlyList<Hero>) this._lordsCache;

    public MBReadOnlyList<WarPartyComponent> WarPartyComponents
    {
      get => (MBReadOnlyList<WarPartyComponent>) this._warPartyComponentsCache;
    }

    public float DailyCrimeRatingChange
    {
      get
      {
        return Campaign.Current.Models.CrimeModel.GetDailyCrimeRatingChange((IFaction) this).ResultNumber;
      }
    }

    public ExplainedNumber DailyCrimeRatingChangeExplained
    {
      get => Campaign.Current.Models.CrimeModel.GetDailyCrimeRatingChange((IFaction) this, true);
    }

    public CharacterObject BasicTroop => this.Culture.BasicTroop;

    public Hero Leader => this._rulingClan?.Leader;

    [SaveableProperty(16)]
    public Banner Banner { get; private set; }

    public bool IsBanditFaction => false;

    public bool IsMinorFaction => false;

    bool IFaction.IsKingdomFaction => true;

    public bool IsRebelClan => false;

    public bool IsClan => false;

    public bool IsOutlaw => false;

    public MBReadOnlyList<Clan> Clans => (MBReadOnlyList<Clan>) this._clans;

    public Clan RulingClan
    {
      get => this._rulingClan;
      set => this._rulingClan = value;
    }

    [SaveableProperty(19)]
    public int LastArmyCreationDay { get; private set; }

    public MBReadOnlyList<Army> Armies => (MBReadOnlyList<Army>) this._armies;

    public override string ToString() => this.Name.ToString();

    public float TotalStrength
    {
      get
      {
        float totalStrength = 0.0f;
        int count = this._clans.Count;
        for (int index = 0; index < count; ++index)
          totalStrength += this._clans[index].TotalStrength;
        return totalStrength;
      }
    }

    [CachedData]
    internal bool _midPointCalculated { get; set; }

    public float DistanceToClosestNonAllyFortification
    {
      get
      {
        if (this._distanceToClosestNonAllyFortificationCacheDirty)
        {
          this._distanceToClosestNonAllyFortificationCache = FactionHelper.GetDistanceToClosestNonAllyFortificationOfFaction((IFaction) this);
          this._distanceToClosestNonAllyFortificationCacheDirty = false;
        }
        return this._distanceToClosestNonAllyFortificationCache;
      }
    }

    public IList<PolicyObject> ActivePolicies => (IList<PolicyObject>) this._activePolicies;

    public static MBReadOnlyList<Kingdom> All => Campaign.Current.Kingdoms;

    [SaveableProperty(28)]
    public CampaignTime LastKingdomDecisionConclusionDate { get; private set; }

    public bool IsEliminated => this._isEliminated;

    [SaveableProperty(41)]
    public CampaignTime LastMercenaryOfferTime { get; set; }

    public IFaction MapFaction => (IFaction) this;

    [SaveableProperty(50)]
    public CampaignTime NotAttackableByPlayerUntilTime { get; set; }

    public float Aggressiveness
    {
      get => this._aggressiveness;
      internal set => this._aggressiveness = MathF.Clamp(value, 0.0f, 100f);
    }

    public IEnumerable<MobileParty> AllParties
    {
      get
      {
        Kingdom kingdom = this;
        foreach (MobileParty mobileParty in (List<MobileParty>) Campaign.Current.MobileParties)
        {
          if (mobileParty.MapFaction == kingdom)
            yield return mobileParty;
        }
      }
    }

    public Settlement FactionMidSettlement
    {
      get
      {
        if (!this._midPointCalculated)
          this.UpdateFactionMidPoint();
        return this._kingdomMidSettlement;
      }
    }

    [SaveableProperty(70)]
    public int MercenaryWallet { get; internal set; }

    public int TributeWallet
    {
      get => this._tributeWallet;
      set => this._tributeWallet = value;
    }

    public int KingdomBudgetWallet
    {
      get => this._kingdomBudgetWallet;
      set => this._kingdomBudgetWallet = value;
    }

    public Kingdom()
    {
      this._activePolicies = new MBList<PolicyObject>();
      this._armies = new MBList<Army>();
      this.InitializeCachedLists();
      this.EncyclopediaText = TextObject.Empty;
      this.EncyclopediaTitle = TextObject.Empty;
      this.EncyclopediaRulerTitle = TextObject.Empty;
      this.PoliticalStagnation = 10 + (int) ((double) MBRandom.RandomFloat * (double) MBRandom.RandomFloat * 100.0);
      this._midPointCalculated = false;
      this._distanceToClosestNonAllyFortificationCacheDirty = true;
      this._isEliminated = false;
      this.NotAttackableByPlayerUntilTime = CampaignTime.Zero;
      this.LastArmyCreationDay = (int) CampaignTime.Now.ToDays;
      CampaignEvents.OnNewGameCreatedEvent.AddNonSerializedListener((object) this, new Action<CampaignGameStarter>(this.OnNewGameCreated));
    }

    public static Kingdom CreateKingdom(string stringID)
    {
      stringID = Campaign.Current.CampaignObjectManager.FindNextUniqueStringId<Kingdom>(stringID);
      Kingdom kingdom = new Kingdom();
      kingdom.StringId = stringID;
      Campaign.Current.CampaignObjectManager.AddKingdom(kingdom);
      return kingdom;
    }

    public void InitializeKingdom(
      TextObject name,
      TextObject informalName,
      CultureObject culture,
      Banner banner,
      uint kingdomColor1,
      uint kingdomColor2,
      Settlement initialHomeland,
      TextObject encyclopediaText,
      TextObject encyclopediaTitle,
      TextObject encyclopediaRulerTitle)
    {
      this.ChangeKingdomName(name, informalName);
      this.Culture = culture;
      this.Banner = banner;
      this.Color = kingdomColor1;
      this.Color2 = kingdomColor2;
      this.PrimaryBannerColor = this.Color;
      this.SecondaryBannerColor = this.Color2;
      this.InitialHomeLand = initialHomeland;
      this.PoliticalStagnation = 100;
      this.EncyclopediaText = encyclopediaText;
      this.EncyclopediaTitle = encyclopediaTitle;
      this.EncyclopediaRulerTitle = encyclopediaRulerTitle;
      foreach (PolicyObject defaultPolicy in (List<PolicyObject>) this.Culture.DefaultPolicyList)
        this.AddPolicy(defaultPolicy);
    }

    private void InitializeCachedLists()
    {
      this._clans = new MBList<Clan>();
      this._stances = new List<StanceLink>();
      this._fiefsCache = new MBList<Town>();
      this._villagesCache = new MBList<Village>();
      this._settlementsCache = new MBList<Settlement>();
      this._heroesCache = new MBList<Hero>();
      this._lordsCache = new MBList<Hero>();
      this._warPartyComponentsCache = new MBList<WarPartyComponent>();
    }

    public void ChangeKingdomName(TextObject name, TextObject informalName)
    {
      this.Name = name;
      this.InformalName = informalName;
    }

    public void OnNewGameCreated(CampaignGameStarter starter)
    {
      this.InitialHomeLand = this.Leader.HomeSettlement;
    }

    [LoadInitializationCallback]
    private void OnLoad(MetaData metaData, ObjectLoadData objectLoadData)
    {
      this.InitializeCachedLists();
    }

    protected override void AfterLoad()
    {
      for (int index = this._activePolicies.Count - 1; index >= 0; --index)
      {
        if (this._activePolicies[index] == null || !this._activePolicies[index].IsReady)
          this._activePolicies.RemoveAt(index);
      }
      for (int index = this.Clans.Count - 1; index >= 0; --index)
      {
        Clan clan = this.Clans[index];
        if (clan.GetStanceWith((IFaction) this).IsAtConstantWar)
        {
          foreach (WarPartyComponent warPartyComponent in clan.WarPartyComponents.ToList<WarPartyComponent>())
          {
            if (warPartyComponent.MobileParty.MapEvent != null && (warPartyComponent.MobileParty.Army == null || warPartyComponent.MobileParty.Army.LeaderParty == warPartyComponent.MobileParty))
              warPartyComponent.MobileParty.MapEvent.FinalizeEvent();
          }
        }
      }
    }

    public bool IsAtWarWith(IFaction other)
    {
      return FactionManager.IsAtWarAgainstFaction((IFaction) this, other);
    }

    internal void AddStanceInternal(StanceLink stanceLink) => this._stances.Add(stanceLink);

    internal void RemoveStanceInternal(StanceLink stanceLink) => this._stances.Remove(stanceLink);

    public StanceLink GetStanceWith(IFaction other)
    {
      return FactionManager.Instance.GetStanceLinkInternal((IFaction) this, other);
    }

    internal void AddArmyInternal(Army army) => this._armies.Add(army);

    internal void RemoveArmyInternal(Army army) => this._armies.Remove(army);

    public void CreateArmy(
      Hero armyLeader,
      Settlement targetSettlement,
      Army.ArmyTypes selectedArmyType)
    {
      if (!armyLeader.IsActive)
      {
        Debug.Print(string.Format("Failed to create army, leader - {0}: {1} is inactive", (object) armyLeader?.StringId, (object) armyLeader?.Name));
      }
      else
      {
        Army.ArmyTypes armyType = selectedArmyType;
        if (armyLeader?.PartyBelongedTo.LeaderHero != null)
        {
          Army army = new Army(this, armyLeader.PartyBelongedTo, armyType)
          {
            AIBehavior = Army.AIBehaviorFlags.Gathering
          };
          army.Gather(targetSettlement);
          this.LastArmyCreationDay = (int) CampaignTime.Now.ToDays;
          CampaignEventDispatcher.Instance.OnArmyCreated(army);
        }
        if (armyLeader != Hero.MainHero || !(Game.Current.GameStateManager.GameStates.Single<TaleWorlds.Core.GameState>((Func<TaleWorlds.Core.GameState, bool>) (S => S is MapState)) is MapState mapState))
          return;
        mapState.OnArmyCreated(MobileParty.MainParty);
      }
    }

    private void UpdateFactionMidPoint()
    {
      this._kingdomMidSettlement = FactionHelper.FactionMidSettlement((IFaction) this);
      this._midPointCalculated = this._kingdomMidSettlement != null;
    }

    public void AddDecision(KingdomDecision kingdomDecision, bool ignoreInfluenceCost = false)
    {
      if (!ignoreInfluenceCost)
      {
        Clan proposerClan = kingdomDecision.ProposerClan;
        int influenceCost = kingdomDecision.GetInfluenceCost(proposerClan);
        ChangeClanInfluenceAction.Apply(proposerClan, (float) -influenceCost);
      }
      bool isPlayerInvolved = kingdomDecision.DetermineChooser().Leader.IsHumanPlayerCharacter || kingdomDecision.DetermineSupporters().Any<Supporter>((Func<Supporter, bool>) (x => x.IsPlayer));
      CampaignEventDispatcher.Instance.OnKingdomDecisionAdded(kingdomDecision, isPlayerInvolved);
      if (kingdomDecision.Kingdom != Clan.PlayerClan.Kingdom)
        new KingdomElection(kingdomDecision).StartElection();
      else
        this._unresolvedDecisions.Add(kingdomDecision);
    }

    public void RemoveDecision(KingdomDecision kingdomDecision)
    {
      this._unresolvedDecisions.Remove(kingdomDecision);
    }

    public void OnKingdomDecisionConcluded()
    {
      this.LastKingdomDecisionConclusionDate = CampaignTime.Now;
    }

    public void AddPolicy(PolicyObject policy)
    {
      if (this._activePolicies.Contains(policy))
        return;
      this._activePolicies.Add(policy);
    }

    public void RemovePolicy(PolicyObject policy)
    {
      if (!this._activePolicies.Contains(policy))
        return;
      this._activePolicies.Remove(policy);
    }

    public bool HasPolicy(PolicyObject policy)
    {
      for (int index = 0; index < this._activePolicies.Count; ++index)
      {
        if (this._activePolicies[index] == policy)
          return true;
      }
      return false;
    }

    public override void Deserialize(MBObjectManager objectManager, XmlNode node)
    {
      base.Deserialize(objectManager, node);
      this.EncyclopediaText = node.Attributes["text"] != null ? new TextObject(node.Attributes["text"].Value) : TextObject.Empty;
      this.EncyclopediaTitle = node.Attributes["title"] != null ? new TextObject(node.Attributes["title"].Value) : TextObject.Empty;
      this.EncyclopediaRulerTitle = node.Attributes["ruler_title"] != null ? new TextObject(node.Attributes["ruler_title"].Value) : TextObject.Empty;
      this.InitializeKingdom(new TextObject(node.Attributes["name"].Value), node.Attributes["short_name"] != null ? new TextObject(node.Attributes["short_name"].Value) : new TextObject(node.Attributes["name"].Value), (CultureObject) objectManager.ReadObjectReferenceFromXml("culture", typeof (CultureObject), node), (Banner) null, node.Attributes["color"] == null ? 0U : Convert.ToUInt32(node.Attributes["color"].Value, 16), node.Attributes["color2"] == null ? 0U : Convert.ToUInt32(node.Attributes["color2"].Value, 16), (Settlement) null, this.EncyclopediaText, this.EncyclopediaTitle, this.EncyclopediaRulerTitle);
      this.RulingClan = objectManager.ReadObjectReferenceFromXml("owner", typeof (Hero), node) is Hero hero ? hero.Clan : (Clan) null;
      this.LabelColor = node.Attributes["label_color"] == null ? 0U : Convert.ToUInt32(node.Attributes["label_color"].Value, 16);
      this.AlternativeColor = node.Attributes["alternative_color"] == null ? 0U : Convert.ToUInt32(node.Attributes["alternative_color"].Value, 16);
      this.AlternativeColor2 = node.Attributes["alternative_color2"] == null ? 0U : Convert.ToUInt32(node.Attributes["alternative_color2"].Value, 16);
      this.PrimaryBannerColor = node.Attributes["primary_banner_color"] == null ? 0U : Convert.ToUInt32(node.Attributes["primary_banner_color"].Value, 16);
      this.SecondaryBannerColor = node.Attributes["secondary_banner_color"] == null ? 0U : Convert.ToUInt32(node.Attributes["secondary_banner_color"].Value, 16);
      if (node.Attributes["banner_key"] != null)
      {
        this.Banner = new Banner();
        this.Banner.Deserialize(node.Attributes["banner_key"].Value);
      }
      else
        this.Banner = Banner.CreateRandomClanBanner(this.StringId.GetDeterministicHashCode());
      foreach (XmlNode childNode1 in node.ChildNodes)
      {
        if (childNode1.Name == "relationships")
        {
          foreach (XmlNode childNode2 in childNode1.ChildNodes)
          {
            IFaction faction2 = childNode2.Attributes["clan"] == null ? (IFaction) objectManager.ReadObjectReferenceFromXml("kingdom", typeof (Kingdom), childNode2) : (IFaction) objectManager.ReadObjectReferenceFromXml("clan", typeof (Clan), childNode2);
            int int32 = Convert.ToInt32(childNode2.Attributes["value"].InnerText);
            if (int32 > 0)
              FactionManager.DeclareAlliance((IFaction) this, faction2);
            else if (int32 < 0)
              FactionManager.DeclareWar((IFaction) this, faction2);
            else
              FactionManager.SetNeutral((IFaction) this, faction2);
            if (childNode2.Attributes["isAtWar"] != null && Convert.ToBoolean(childNode2.Attributes["isAtWar"].Value))
              FactionManager.DeclareWar((IFaction) this, faction2);
          }
        }
        else if (childNode1.Name == "policies")
        {
          foreach (XmlNode childNode3 in childNode1.ChildNodes)
          {
            PolicyObject policy = Game.Current.ObjectManager.GetObject<PolicyObject>(childNode3.Attributes["id"].Value);
            if (policy != null)
              this.AddPolicy(policy);
          }
        }
      }
    }

    internal void AddClanInternal(Clan clan)
    {
      this._clans.Add(clan);
      this._midPointCalculated = false;
      this._distanceToClosestNonAllyFortificationCacheDirty = true;
    }

    internal void RemoveClanInternal(Clan clan)
    {
      this._clans.Remove(clan);
      this._midPointCalculated = false;
      this._distanceToClosestNonAllyFortificationCacheDirty = true;
    }

    public void OnFortificationAdded(Town fief)
    {
      this._fiefsCache.Add(fief);
      this._settlementsCache.Add(fief.Settlement);
      foreach (Village boundVillage in (List<Village>) fief.Settlement.BoundVillages)
        this.OnBoundVillageAdded(boundVillage);
    }

    public void OnFiefRemoved(Town fief)
    {
      this._fiefsCache.Remove(fief);
      this._settlementsCache.Remove(fief.Settlement);
      foreach (Village boundVillage in (List<Village>) fief.Settlement.BoundVillages)
      {
        this._villagesCache.Remove(boundVillage);
        this._settlementsCache.Remove(boundVillage.Settlement);
      }
    }

    internal void OnBoundVillageAdded(Village village)
    {
      this._villagesCache.Add(village);
      this._settlementsCache.Add(village.Settlement);
    }

    public void OnHeroAdded(Hero hero)
    {
      this._heroesCache.Add(hero);
      if (hero.Occupation != Occupation.Lord)
        return;
      this._lordsCache.Add(hero);
    }

    public void OnHeroRemoved(Hero hero)
    {
      this._heroesCache.Remove(hero);
      if (hero.Occupation != Occupation.Lord)
        return;
      this._lordsCache.Remove(hero);
    }

    public void OnWarPartyAdded(WarPartyComponent warPartyComponent)
    {
      this._warPartyComponentsCache.Add(warPartyComponent);
    }

    public void OnWarPartyRemoved(WarPartyComponent warPartyComponent)
    {
      this._warPartyComponentsCache.Remove(warPartyComponent);
    }

    public void ReactivateKingdom() => this._isEliminated = false;

    internal void DeactivateKingdom() => this._isEliminated = true;

    [SpecialName]
    string IFaction.get_StringId() => this.StringId;

    [SpecialName]
    MBGUID IFaction.get_Id() => this.Id;
  }
}
